require("dotenv").config();

const express = require("express");
const cors = require("cors");
const { authenticateSerial } = require("./config/auth");
const imageTranslateService = require("./services/image-translate");
const { logger, httpLogger } = require("./config/logger");
const http = require("http");
const path = require('path');

const { initDatabase, closeDatabase } = require("./config/database");

initDatabase();

const app = express();


// 创建 HTTP 服务器
const server = http.createServer(app);

// Middleware
app.use(cors());
app.use(httpLogger); // 添加 HTTP 请求日志

// 记录请求体的中间件
app.use((req, res, next) => {
  // 克隆请求体，避免修改原始数据
  const requestBody = JSON.parse(JSON.stringify(req.body || {}));

  // 如果包含语音或图片数据，记录其长度而不是具体内容
  if (requestBody.voice) {
    requestBody.voice = `<Base64 Audio Data Length: ${requestBody.voice.length} chars>`;
  }
  if (requestBody.image) {
    requestBody.image = `<Base64 Image Data Length: ${requestBody.image.length} chars>`;
  }

  logger.info("Request Details", {
    method: req.method,
    url: req.url,
    headers: req.headers,
    query: req.query,
    body: requestBody,
    ip: req.ip,
  });

  // 捕获响应体
  const originalJson = res.json;
  res.json = function (body) {
    // 克隆响应体，避免修改原始数据
    const responseBody = JSON.parse(JSON.stringify(body));

    // 如果响应包含音频或图片数据，记录其长度而不是具体内容
    if (responseBody.result?.target_tts) {
      responseBody.result.target_tts = `<Base64 Audio Data Length: ${responseBody.result.target_tts.length} chars>`;
    }
    if (responseBody.result?.pasteImg) {
      responseBody.result.pasteImg = `<Base64 Image Data Length: ${responseBody.result.pasteImg.length} chars>`;
    }

    logger.info("Response Details", {
      method: req.method,
      url: req.url,
      statusCode: res.statusCode,
      body: responseBody,
      ip: req.ip,
      responseTime: Date.now() - req._startTime,
    });

    originalJson.call(this, body);
  };

  req._startTime = Date.now();
  next();
});

app.use(express.json({ limit: "6mb" })); // Increased limit for base64 data
// Health check endpoint
app.get("/health", (req, res) => {
  res.json({ status: "ok" });
});

// 百度图片翻译 endpoint
app.post("/api/translate/image", authenticateSerial, async (req, res) => {
  try {
    const { image, from, to, paste_type } = req.body;

    // Validate required fields
    if (!image || !from || !to) {
      logger.warn("Missing required fields in image translation request", {
        from,
        to,
        hasImage: !!image,
        ip: req.ip,
      });
      return res.status(400).json({
        error: "Missing required fields",
        message: "image, from, and to are required",
      });
    }

    // Convert base64 to buffer
    let imageBuffer;
    try {
      // Remove data URL prefix if present
      const base64Data = image.replace(/^data:image\/\w+;base64,/, "");
      imageBuffer = Buffer.from(base64Data, "base64");
    } catch (error) {
      logger.error("Failed to decode base64 image", {
        error: error.message,
        ip: req.ip,
      });
      return res.status(400).json({
        error: "Invalid image data",
        message: "Failed to decode base64 image data",
      });
    }

    // Validate image data size (4MB limit)
    if (imageBuffer.length > 4 * 1024 * 1024) {
      logger.warn("Image data size exceeds limit", {
        size: imageBuffer.length,
        ip: req.ip,
      });
      return res.status(400).json({
        error: "Image data too large",
        message: "Image data exceeds 4MB limit",
      });
    }

    logger.info("Processing image translation request", {
      from,
      to,
      pasteType: paste_type || 1,
      imageDataLength: imageBuffer.length,
      ip: req.ip,
    });

    const result = await imageTranslateService.translateImage(
      imageBuffer,
      from,
      to,
      paste_type || 1
    );

    logger.info("Image translation successful", {
      from: result.result.from,
      to: result.result.to,
      hasTranslatedImage: !!result.result.pasteImg,
      ip: req.ip,
      logId: result.log_id,
    });

    res.json(result);
  } catch (error) {
    logger.error("Image translation error", {
      error: error.message,
      stack: error.stack,
      ip: req.ip,
      requestBody: {
        from: req.body.from,
        to: req.body.to,
        paste_type: req.body.paste_type,
        imageDataLength: req.body.image?.length,
      },
    });

    res.status(500).json({
      error: "Image translation failed",
      message: error.message,
    });
  }
});

app.get("/api/zego/token", async (req, res) => {
  try {
    const { roomId, userId, expire = "3600", needPublish = "true" } = req.query;

    if (!roomId || !userId) {
      return res.status(400).json({ code: 400, message: "roomId 和 userId 为必填", success: false });
    }

    const allowPublish = needPublish === "true" || needPublish === "1";
    const expireSeconds = parseInt(expire, 10) || 3600;

    const token = require("./services/zego-token").createToken({
      roomId,
      userId,
      expire: expireSeconds,
      allowPublish,
    });

    res.json({
      code: 200,
      message: "获取Token成功",
      data: {
        token,
        appId: parseInt(process.env.ZEGO_APP_ID, 10),
        expire: expireSeconds,
      },
      success: true,
    });
  } catch (error) {
    console.error("生成 Zego token 失败", error);
    res.status(500).json({ code: 500, message: "服务器内部错误", success: false });
  }
});

// Error handling middleware
app.use((err, req, res, next) => {
  logger.error("Unhandled error", {
    error: err.message,
    stack: err.stack,
    ip: req.ip,
    method: req.method,
    url: req.url,
    headers: req.headers,
    query: req.query,
    body: req.body,
  });

  res.status(500).json({
    error: "Internal server error",
    message:
      process.env.NODE_ENV === "production"
        ? "An unexpected error occurred"
        : err.message,
  });
});

// 静态托管前端资源
app.use('/invite', express.static(path.join(__dirname, 'frontend')));

// 提供全局静态 JS 资源
app.use('/assets', express.static(path.join(__dirname, '..', 'assets')));

// 支持参数化的邀请链接，始终返回 index.html
app.get('/invite/:roomId/:sourceLang/:targetLang', (req, res) => {
  res.sendFile(path.join(__dirname, 'frontend', 'index.html'));
});

// 修改服务器启动代码
const PORT = process.env.PORT || 3000;
server.listen(PORT, "0.0.0.0", () => {  // 绑定到所有网络接口
  logger.info(`Server is running on port ${PORT}`);
});

// 优雅关闭处理
process.on('SIGINT', async () => {
  console.log('收到 SIGINT，开始优雅关闭...');
  try {
    await closeDatabase();
    server.close(() => {
      console.log('服务器已关闭');
      process.exit(0);
    });
  } catch (error) {
    console.error('关闭过程出错:', error);
    process.exit(1);
  }
});

process.on('SIGTERM', async () => {
  console.log('收到 SIGTERM，开始优雅关闭...');
  try {
    await closeDatabase();
    server.close(() => {
      console.log('服务器已关闭');
      process.exit(0);
    });
  } catch (error) {
    console.error('关闭过程出错:', error);
    process.exit(1);
  }
});